// part1:C09:ex9.28.cpp
// find a string, and insert second string after fist string.
//  if not find first string, insert second string to the end of forward_list.
#include <forward_list>
#include <iostream>

using namespace std;
void test_and_insert(forward_list<string> &sflist, const string &s1,
                     const string &s2) {
  auto prev = sflist.before_begin();
  auto curr = sflist.begin();
  bool isinserted = false;

  while (curr != sflist.end()) {
    if (*curr == s1) {
      curr = sflist.insert_after(curr, s2);
      isinserted = true;
    }
    prev = curr;
    curr++;
  }

  if (!isinserted) {
    sflist.insert_after(prev, s2); // insert end of forward_list
  }
}

int main(void) {
  forward_list<string> sflist = {"Hello", "!", "World", "!"};
  test_and_insert(sflist, "Hello", "nihao");
  for (auto curr = sflist.cbegin(); curr != sflist.cend(); curr++) {
    cout << *curr << " ";
  }
  cout << endl;

  test_and_insert(sflist, "!", "?");
  for (auto curr = sflist.cbegin(); curr != sflist.cend(); curr++) {
    cout << *curr << " ";
  }
  cout << endl;

  test_and_insert(sflist, "Bye", "zaijian");
  for (auto curr = sflist.cbegin(); curr != sflist.cend(); curr++) {
    cout << *curr << " ";
  }
  cout << endl;
  return 0;
}
